import model.Book;
import model.BookDB;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/purchase")
public class PurcharseServlet extends HttpServlet {

    private static List<Book> cart = new ArrayList<>();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应编码为UTF-8，避免中文乱码
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String bookId = request.getParameter("bookId");
        Book book = BookDB.getBookById(bookId);

        if (book!= null) {
            cart.add(book);
            out.println("{ \"success\": true }");
        } else {
            out.println("{ \"success\": false }");
        }
    }

    public static List<Book> getCart() {
        return cart;
    }
}

